//
// Created by YxMin on 2024/7/5.
//
#include <cstdio>
#include <netdata.h>
#include "network.h"
#include <cstring>
//room
bool ParseIpFromRoomButtonText(char* btnText, char* dest)
{
    int count = -1;
    while(*btnText) {
        if (*btnText == '[') {
            count = 0;
            btnText++;
        }
        if (*btnText == ']' && count < 16) {
            dest[count] = 0;
            return true;
        }
        if (count >= 16)
            break;
        if (count >= 0) {
            dest[count] = *btnText;
            count ++;
        }
        btnText++;
    }
    return false;
}
bool QueueSendDataToClientAndKickIfFail(int id, char* data) {
    if (!QueueSendDataToClient(id,data)) {
        KickClient(id);
        SendPlayerQuitPack(id, data); //复用data的内存作为buffer
        return false;
    }
    return true;
}
bool BroadcastDataToClientExceptAndKickIfFail(char* data, int exceptId/* = -1*/) {
    int *failedIds,*p;
    if(!BroadcastDataToClientExcept(data,exceptId,failedIds)) {
        p = failedIds;
        while(*p != -1) {
            KickClient(*p);
            SendPlayerQuitPack(*p, data); //存在二者的递归调用，但好像没问题，再看看吧
            p++;
        }
        delete failedIds;
        return false;
    }
    return true;
}
//server
bool SendPlayerIdSetPack(int id, char* buffer) {
    sprintf(buffer,"<[1%d]>",id);
    return QueueSendDataToClientAndKickIfFail(id, buffer);//queue之后会把buffer内容复制到队列里
}
bool SendRoomFullPack(int id) {
    return QueueSendDataToClientAndKickIfFail(id, "<[01]>");
}
bool SendPlayerJoinPack(int id, char* buffer) {
    sprintf(buffer,"<[2%d]>",id);
    return BroadcastDataToClientExceptAndKickIfFail(buffer, id);
}
bool SendPlayerQuitPack(int id, char* buffer) {
    sprintf(buffer,"<[3%d]>",id);
    return BroadcastDataToClientExceptAndKickIfFail(buffer, id);
}
bool SendGameStartPack() {
    return BroadcastDataToClientExceptAndKickIfFail("<[40]>");
}
bool SendRoomOverPack() {
    return BroadcastDataToClientExceptAndKickIfFail("<[50]>",0);
}
bool SendPlayerListPack(int id,char* buffer) {
    buffer[0] = '<';
    buffer[1] = '[';
    buffer[2] = '7';
    char* p = &buffer[3];
    for (int i = 0; i < 4; ++i) {
        if (IsClientOnline(i)) {
            *p = (char)i | 0x30;
            p++;
        }
    }
    strcpy(p,"]>");
    return QueueSendDataToClientAndKickIfFail(id, buffer);
}
//client
char clientSendBuffer[128];
bool SendJoinRequest() {
    return QueueSendDataToServer("<[00]>");
}
bool SendQuitRequest(int id) {
    sprintf(clientSendBuffer,"<[3%d]>",id);
    return QueueSendDataToServer(clientSendBuffer);
}
bool SendBackRequest(int id) {
    sprintf(clientSendBuffer,"<[6%d]>",id);
    return QueueSendDataToServer(clientSendBuffer);
}
bool ResponseGameStartPack() {
    return QueueSendDataToServer("<[40]>");
}